﻿@page "/calculateunits/index"
@attribute [Authorize]

@inject DialogService DialogService
@inject ICalculateUnitService CalculateUnitService

<RadzenCard Variant="Variant.Filled" Style="height : 100%;">
    <RadzenStack>
        <SearchFormPartial Model="_searchRequestDto" QueryHandler="QueryHandler"></SearchFormPartial>
        <SearchTablePartial @ref="_requestTable" T="CalculateUnitInfoResponseDto" ServerData="ServerReload"
                            SearchPartial="_searchPartial" AddHandler="AddHandler" EditHandler="EditHandler">

        </SearchTablePartial>

    </RadzenStack>

</RadzenCard>

@code {
    private CalculateUnitSearchRequestDto _searchRequestDto = new();
    private IEnumerable<CalculateUnitInfoResponseDto> _pagedData = new List<CalculateUnitInfoResponseDto>();
    private SearchPartialInfo _searchPartial = new();
    private SearchTablePartial<CalculateUnitInfoResponseDto> _requestTable = new();
    private int _totalItems;

    async Task QueryHandler(MouseEventArgs args)
    {
        await _requestTable.ReloadServerData();
    }

    async Task AddHandler(MouseEventArgs args)
    {
        await DialogService.OpenAsync<CalculateUnitEdit>("Add CalculateUnit", null);
        await _requestTable.ReloadServerData();
    }

    async Task EditHandler(MouseEventArgs args, CalculateUnitInfoResponseDto model)
    {
        await DialogService.OpenAsync<CalculateUnitEdit>("Edit CalculateUnit", new Dictionary<string, object> { { "Key", model.Id } });
        await _requestTable.ReloadServerData();
    }

    /// <summary>
    /// Here we simulate getting the paged, filtered and ordered data from the server
    /// </summary>
    private async Task<ODataServiceResult<CalculateUnitInfoResponseDto>> ServerReload(LoadDataArgs state)
    {
        if (state.Skip != null) _searchRequestDto.Page = (int)(state.Skip + 1);
        if (state.Top != null) _searchRequestDto.Limit = (int)state.Top;
        var result = await CalculateUnitService.QueryCalculateUnitsByPage(_searchRequestDto);

        if (result is { Succeeded: true })
        {
            _pagedData = result.Data;
            _totalItems = result.TotalCount;
        }

        return new ODataServiceResult<CalculateUnitInfoResponseDto>() { Count = _totalItems, Value = _pagedData };
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

    //var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();

        _searchPartial.IsAdd = true;
        _searchPartial.IsEdit = true;
        _searchPartial.IsDelete = true;
    }


}